import { defineStore } from 'pinia';
// import { useRouter } from 'vue-router';
import router from '@/router/index';
import StorageService from '@/services/storage';
import { LOCALSTORAGE_SIDEBARSTATUS } from '@/config';
export const useAppStore = defineStore('app', {
  state: () => {
    return {
      dynamicRoutes: [], // 动态路由数据
      dynamicRoutesState: false, // 是否加载了动态路由
      sidebar: {
        collapsed: StorageService.getLocal(LOCALSTORAGE_SIDEBARSTATUS, false)
      }
    };
  },
  getters: {
    // 所有有权限的菜单
    menusList: (state: any) => {
      const menus = [
        { name: 'Kgj', title: '考古加' },
        { name: 'Cy', title: '创意' },
        { name: 'Dyj', title: '大赢加' },
        { name: 'Agency', title: '分销系统' },
        { name: 'Content', title: '内容管理系统' },
        { name: 'Beta', title: '开票系统', link: 'https://crm.kaogujia.com/beta' }
      ];
      const maps = menus.reduce((a: any, b: any) => {
        a[b.name] = b;
        return a;
      }, {});
      const routes = state.dynamicRoutes || [];
      routes.forEach((o: any) => {
        let tMenu = null;
        if (o.name && (tMenu = maps[o.name])) {
          tMenu.children = o.children || [];
        }
      });
      return menus;
    },
    topMenuMap: (state: any) => {
      return state.menusList.reduce((a: any, b: any) => {
        a[b.name] = b;
        return a;
      }, {});
    },
    // 把路由name 和 topMenu的name 构建map， 方便查询
    validMenusNameMap: (state: any) => {
      const map = {};
      state.menusList.forEach((menu: any) => {
        if (menu.children?.length) {
          menu.children.forEach((o: any) => setMap(menu.name, map, o));
        }
      });

      function setMap(topMenuName: string, map: any, child: any) {
        if (child.name) map[child.name] = topMenuName;
        if (child.children && child.children.length) {
          child.children.forEach((o: any) => setMap(topMenuName, map, o));
        }
      }

      return map;
    },
    /** 当前顶部菜单对应的 name 值 */
    currentTopMenuName: (state: any) => {
      const currentRoute = router.currentRoute;
      const routeName = currentRoute.value.name;
      const name = (routeName && state.validMenusNameMap[routeName]) || state.sysMenus?.[0].name || '';
      return name;
    },
    currentTopMenu: (state: any) => {
      if (state.currentTopMenuName) {
        return state.topMenuMap[state.currentTopMenuName] || {};
      } else {
        return {};
      }
    },
    currentAsideMenus: (state: any) => {
      return state.currentTopMenu?.children || [];
    }
  },
  actions: {
    setDynamicRoutes(routes: any = []) {
      this.dynamicRoutes = routes;
    },
    setDynamicRoutesState(state?: boolean) {
      this.dynamicRoutesState = !!state;
    },
    toggleSidebar(val: boolean) {
      this.sidebar.collapsed = val;
      StorageService.setLocal(LOCALSTORAGE_SIDEBARSTATUS, val);
    }
  }
});

